package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.*;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.*;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.R;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.GetQnTokenMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.task.DownloadImageTask;
import com.lzx.iteam.util.*;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

/**
 * Created by hfx on 14-7-20.
 */
public class EditMyCardActivity extends Activity implements View.OnClickListener, View.OnTouchListener {
    private EditText mCardName;
    private EditText mCardPosition;
    private EditText mCardMobilePhone;
    private EditText mCardCompany;
    private EditText mCardEmail;
    private EditText mCardAddress;
    private ImageView mCardPhoto;
    private TextView mBtnSave;
    private TextView mSex;
    private LinearLayout mBack;
    private LinearLayout mLlNoteLayout;
    private RelativeLayout mRlSexLayout;
    private FrameLayout mFlPhoto;
    private ScrollView mScrollView;
    private PopupWindow mSetSexPop;
    private View mAddressLine;

    private ArrayList<String> mContactDataList;
    private boolean isChange; // 判断名片是否修改

    // 设置头像相关
    private PopupWindow mSetPhotoPop;
    private LinearLayout mMainView;
    private File mCurrentPhotoFile;
    private Bitmap imageBitmap;
    private Uri imageUri;
    private Uri mAvatarUri;
    private static final String IMAGE_FILE = Environment.getExternalStorageDirectory()+"/Yun/Images";
    private static final String IMAGE_FILE_LOCATION = Environment.getExternalStorageDirectory()+"/Yun/Images/avatar_crop";
    private static final String IMAGE_FILE_PHOTO = Environment.getExternalStorageDirectory()+"/Yun/Images/avatar_test";

    private static final int ICON_SIZE = 480;
    private static final int PHOTO_PICKED_WITH_DATA = 1881;
    private static final int CAMERA_WITH_DATA = 1884;
    private static final int SETTING_CARD = 1886;
    private static final int GET_QN_TOKEN = 1888;

    private PreferenceUtil mPreferenceUtil;

    // 名片相关
    private String name, position, mobilePhone1, mobilePhone2, email, address, company, avatar;
    private String sex = "0";


    private Context mContext;
    private Dialog mDialog;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SETTING_CARD:
                    mDialog.dismiss();
                    if (msg.arg1 == 0) {
                        ArrayList<String> cardData = new ArrayList<String>();
                        JSONObject object = (JSONObject) msg.obj;
                        try {
                            JSONObject data = object.getJSONObject("data");
                            if (data != null) {
                                cardData.add(data.getString("user_name"));
                                cardData.add(mobilePhone1);
                                cardData.add("1234567890");
                                cardData.add(data.getString("company"));
                                cardData.add(data.getString("job"));
                                cardData.add(email);
                                cardData.add(data.getString("address"));
                                cardData.add(avatar);
                                cardData.add(sex);
                            }else{
                                cardData.add(name);
                                cardData.add(mobilePhone1);
                                cardData.add("1234567890");
                                cardData.add(company);
                                cardData.add(position);
                                cardData.add(email);
                                cardData.add(address);
                                cardData.add(avatar);
                                cardData.add(sex);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        mPreferenceUtil.saveCloudContact(Constants.CONTACT_NAME_CARD, cardData);
                        Toast.makeText(mContext, "修改成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mContext, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mContext, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case GET_QN_TOKEN:
                    if (msg.arg1 == 0) {
                        Map<String, Object> map = (HashMap<String, Object>) msg.obj;
                        String token = (String) map.get("token");
                        byte[] file = (byte[]) map.get("file");
                        String fileName = (String) map.get("fileName");
                        setPhoto(token, file, fileName);
                    }
                    break;
            }
        }
    };


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.function_card_edit_layout);
        mContext = this;
        mDialog = AllDialogUtil.getInstance(this).waitDialog();
        mPreferenceUtil = PreferenceUtil.getInstance(mContext);
        initView();
        getIntentData();
        initCardData();
    }

    /**
     * 保存名片信息
     * 如果只修改了头像，其他没有变化就不走修改名片的接口
     */
    private void savaCardData() {

        String tName = mCardName.getText().toString().trim();
        String tPosition = mCardPosition.getText().toString().trim();
        String tMobilePhone1 = mCardMobilePhone.getText().toString().trim();
//        String tMobilePhone2 = mCardMobilePhoneMore.getText().toString().trim();
        String tEmail = mCardEmail.getText().toString().trim();
        String tCompany = mCardCompany.getText().toString().trim();
        String tAddress = mCardAddress.getText().toString().trim();
        String tSex = "0";
        if ("男".equals(mSex.getText().toString().trim())) {
            tSex = "1";
        } else if ("女".equals(mSex.getText().toString().trim())) {
            tSex = "2";
        } else {
            tSex = "0";
        }
        if (!tName.equals(name)) {
            name = tName;
            isChange = true;
        }
        if (!tPosition.equals(position)) {
            position = tPosition;
            isChange = true;
        }
        if (!tMobilePhone1.equals(mobilePhone1)) {
            mobilePhone1 = tMobilePhone1;
            isChange = true;
        }
//        if (!tMobilePhone2.equals(mobilePhone2)){
//            mobilePhone2 = tMobilePhone2;
//            isChange = true;
//        }
        if (!tSex.equals(sex)) {
            sex = tSex;
            isChange = true;
        }
        if (!tEmail.equals(email)) {
            email = tEmail;
            isChange = true;
        }
        if (!tCompany.equals(company)) {
            company = tCompany;
            isChange = true;
        }
        if (!tAddress.equals(address)) {
            address = tAddress;
            isChange = true;
        }

        if (isChange) {
            if (StringUtil.isEmpty(name)) {
                Toast.makeText(mContext, "姓名不能为空", Toast.LENGTH_SHORT).show();
            }else if (!StringUtil.isEmpty(email) && !StringUtil.checkEmail(email)){
                Toast.makeText(mContext, "邮箱格式不正确", Toast.LENGTH_SHORT).show();
            } else {
                mDialog.show();
                nameMessage(name, mobilePhone2, company, position, email, address, sex);
            }
        } else {
            finish();
        }
    }

    public void nameMessage(String name, String landline, String company, String job, String email, String address, String sex) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_NAME, name));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_LANDLINE, landline));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_COMPANY, company));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_JOB, job));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_EMAIL, email));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ADDRESS, address));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SEX, sex));
//        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_EDIT_TYPE, sex));
//        MySettingActivity.NameMessage message = new MySettingActivity.NameMessage(mHandler.obtainMessage(SETTING_CARD));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(SETTING_CARD));
        message.mApi = AsynHttpClient.API_USER_GOON;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execUserHttp(message);

    }

    /**
     * 获取Intent信息
     */
    private void getIntentData() {
        Intent editIntent = getIntent();
        mContactDataList = editIntent.getStringArrayListExtra("contact_data");
    }

    /**
     * 初始化已有名片信息
     */
    private void initCardData() {
        if (mContactDataList != null) {
            name = mContactDataList.get(0);
            mCardName.setText(name);
            mCardName.setSelection(name.length());
            company = mContactDataList.get(3);
            mCardCompany.setText(company);
            position = mContactDataList.get(4);
            mCardPosition.setText(position);
            mobilePhone1 = mContactDataList.get(1);
            mCardMobilePhone.setText(mobilePhone1);
//            mobilePhone2 = mContactDataList.get(2);
//            mCardMobilePhoneMore.setText(mobilePhone2);


            email = mContactDataList.get(5);
            mCardEmail.setText(email);
            address = mContactDataList.get(6);
            if (!StringUtil.isEmpty(address) && !"None".equals(address)) {
                mCardAddress.setText(address);
            } else {
                mCardAddress.setText("");
            }

            avatar = mContactDataList.get(7);
            if (!StringUtil.isEmpty(avatar) && !"None".equals(avatar)) {
                DownloadImageTask downloadImageTask = new DownloadImageTask(mCardPhoto);
                downloadImageTask.execute(avatar);
            }
            if ("0".equals(mContactDataList.get(8)) ) {
                mSex.setText("未设置");
                mSex.setTextColor(getResources().getColor(R.color.edit_hint));
            } else if ("1".equals(mContactDataList.get(8)) ) {
                mSex.setText("男");
                mSex.setTextColor(getResources().getColor(R.color.edit_text));
            } else if ("2".equals(mContactDataList.get(8)) ) {
                mSex.setText("女");
                mSex.setTextColor(getResources().getColor(R.color.edit_text));
            }

        }
    }


    /**
     * 初始化View布局
     */
    private void initView() {

        mMainView = (LinearLayout) findViewById(R.id.edit_my_layout);
        mCardName = (EditText) findViewById(R.id.cloud_contact_name);
        mCardPosition = (EditText) findViewById(R.id.cloud_contact_position);
        mCardMobilePhone = (EditText) findViewById(R.id.cloud_contact_phone);
        mSex = (TextView) findViewById(R.id.edit_tv_sex);
        mCardMobilePhone.setEnabled(false);
        mCardCompany = (EditText) findViewById(R.id.cloud_contact_company);
        mCardEmail = (EditText) findViewById(R.id.cloud_contact_email);
        mCardAddress = (EditText) findViewById(R.id.cloud_contact_address);
        mRlSexLayout = (RelativeLayout) findViewById(R.id.edit_rl_sex);
        mLlNoteLayout = (LinearLayout) findViewById(R.id.ll_edit_contact_note);
        mRlSexLayout.setOnClickListener(this);
//        mCardMobilePhoneMore = (EditText) findViewById(R.id.et_card_mobile_phone_more);
        mBack = (LinearLayout) findViewById(R.id.edit_my_back);
        mBtnSave = (TextView) findViewById(R.id.edit_my_ok);
        mBtnSave.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mCardPhoto = (ImageView) findViewById(R.id.cloud_contact_photo);
        mFlPhoto = (FrameLayout) findViewById(R.id.edit_fl_image);
        mFlPhoto.setOnClickListener(this);
        mScrollView = (ScrollView) findViewById(R.id.edit_scroll_layout);
        mAddressLine = findViewById(R.id.line_edit_address);
        mAddressLine.setVisibility(View.GONE);
        mLlNoteLayout.setVisibility(View.GONE);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.edit_my_ok:
                savaCardData();
                break;
            case R.id.edit_my_back:
                finish();
                break;
            case R.id.edit_fl_image:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(EditMyCardActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showSetPhotoPop();
                break;
            case R.id.edit_rl_sex:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(EditMyCardActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showSetSexPop();
                break;
            default:
                break;
        }
    }

    /**
     * 弹出拍照和从相册选择popwindow
     */
    private void showSetPhotoPop() {
        View mainView = LayoutInflater.from(this).inflate(R.layout.alert_setphoto_menu_layout, null);
        Button btnTakePhoto = (Button) mainView.findViewById(R.id.btn_take_photo);
        btnTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
                doTakePhoto();
            }
        });
        Button btnCheckFromGallery = (Button) mainView.findViewById(R.id.btn_check_from_gallery);
        btnCheckFromGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
                doPickPhotoFromGallery();
            }
        });
        Button btnCancle = (Button) mainView.findViewById(R.id.btn_cancel);
        btnCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
            }
        });
        mSetPhotoPop = new PopupWindow(this);
        mSetPhotoPop.setBackgroundDrawable(new BitmapDrawable());
        mSetPhotoPop.setFocusable(true);
        mSetPhotoPop.setTouchable(true);
        mSetPhotoPop.setOutsideTouchable(true);
        mSetPhotoPop.setContentView(mainView);
        mSetPhotoPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetPhotoPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetPhotoPop.setAnimationStyle(R.style.bottomStyle);
        mSetPhotoPop.showAtLocation(mMainView, Gravity.BOTTOM, 0, 0);
        mSetPhotoPop.update();

        mainView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mSetPhotoPop.dismiss();
                return false;
            }
        });
    }

    /**
     * 调用系统相机拍照
     */
    protected void doTakePhoto() {
        try {
            File yunDir = new File(IMAGE_FILE);
            if(!yunDir.exists()){
                yunDir.mkdirs();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
            mAvatarUri = Uri.fromFile(new File(IMAGE_FILE_PHOTO));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mAvatarUri);

            /*final Intent intent = getTakePickIntent(mCurrentPhotoFile);*/
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 从相册选择图片
     */
    protected void doPickPhotoFromGallery() {
        try {
            // Launch picker to choose photo for selected contact
            final Intent intent = getPhotoPickIntent();
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 获取调用相册的Intent
     */
    public static Intent getPhotoPickIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        return intent;
    }

    public void getQnToken(byte[] file) {
        String fileName = UUID.randomUUID().toString() + System.currentTimeMillis();
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_KEY, fileName));
        GetQnTokenMsg getQnTokenMsg = new GetQnTokenMsg(mHandler.obtainMessage(GET_QN_TOKEN), file, fileName);
        getQnTokenMsg.mApi = AsynHttpClient.API_QN_GET_US_TOKEN;
        getQnTokenMsg.mParams = mList;
        AsynHttpClient.getInstance(this).execUserHttp(getQnTokenMsg);
    }

    public void setPhoto(String token, byte[] file, String fileName) {
        Log.d("七牛--token", token);
        Log.d("七牛--fileName", fileName);
        DialerApp.getUploadManager(this).put(file, fileName, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject response) {
                        Log.d("七牛--info.isOk()", info.isOK() + "--response" + response);
                        if (response != null) {
                            mCardPhoto.setImageBitmap(imageBitmap);
                            try {
                                avatar = response.getString("data");
                                mPreferenceUtil.save(PreferenceUtil.NAMECARD_AVATAR, avatar);
                                ArrayList<String> cardData = (ArrayList<String>) mPreferenceUtil.getCloudContact(Constants.CONTACT_NAME_CARD);
                                cardData.set(7, avatar);
                                mPreferenceUtil.saveCloudContact(Constants.CONTACT_NAME_CARD, cardData);
                                Toast.makeText(mContext, "修改头像成功", Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else{
                            Toast.makeText(mContext,"失败，请重新设置",Toast.LENGTH_SHORT).show();
                        }
                    }
                }, null);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            switch (requestCode) {
                case PHOTO_PICKED_WITH_DATA:  // 相册
                    startPhotoZoom(data.getData());
                    break;
                case CAMERA_WITH_DATA: // 拍照
                    Bitmap photoBitmap = PhotoUtil.readBitmapFromPath(this,IMAGE_FILE_PHOTO,false);
                    int degree = PhotoUtil.getExifOrientation(IMAGE_FILE_PHOTO);
                    if(degree != 0){
                        photoBitmap = PhotoUtil.rotaingImageView(photoBitmap,degree);
                        if(mCurrentPhotoFile == null){
                            mCurrentPhotoFile = new File(IMAGE_FILE_LOCATION);
                        }
                        mCurrentPhotoFile = PhotoUtil.saveBitmaptoSdCard("avatar_test",photoBitmap,this,"/Yun/Images");
                        startPhotoZoom(Uri.fromFile(mCurrentPhotoFile));
                    }else{
                        startPhotoZoom(mAvatarUri);
                    }
                    break;
                case PHOTO_CROP_RESOULT: // 剪切完

                    try {
                        imageBitmap = getBitmapFromUri(imageUri);
                        getQnToken(PhotoUtil.compressAvatarImage(imageBitmap));
                    }catch (Exception e){
                        Toast.makeText(this,"失败，请重新设置",Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    }


    private Bitmap getBitmapFromUri(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            Log.e("PhotoError " ,"edit_my_card  error  = " + e.toString());
            return null;
        }
        return bitmap;
    }

    /**
     * 093.
     * 收缩图片
     *
     * @param uri
     */
    private final int PHOTO_CROP_RESOULT = 1111;

    public void startPhotoZoom(Uri uri) {
        File yunDir = new File(IMAGE_FILE);
        if(!yunDir.exists()){
            yunDir.mkdirs();
        }
        imageUri = Uri.fromFile(new File(IMAGE_FILE_LOCATION));

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("circleCrop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", ICON_SIZE);
        intent.putExtra("outputY", ICON_SIZE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//图像输出
        intent.putExtra("outputFormat",
                Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);//回调方法data.getExtras().getParcelable("data")返回数据为空
        startActivityForResult(intent, PHOTO_CROP_RESOULT);

    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        try {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 选择性别
     */
    public void showSetSexPop() {
        View mainView = LayoutInflater.from(this).inflate(R.layout.edit_sex_pop_layout, null);
        Button boy = (Button) mainView.findViewById(R.id.edit_sex_boy);
        Button girl = (Button) mainView.findViewById(R.id.edit_sex_girl);
        Button cancel = (Button) mainView.findViewById(R.id.edit_sex_cancle);

        boy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSex.setText("男");
                mSex.setTextColor(getResources().getColor(R.color.black));
                mSetSexPop.dismiss();
            }
        });

        girl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSex.setText("女");
                mSex.setTextColor(getResources().getColor(R.color.black));
                mSetSexPop.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSetSexPop.dismiss();
            }
        });

        mSetSexPop = new PopupWindow(this);
        mSetSexPop.setBackgroundDrawable(new BitmapDrawable());
        mSetSexPop.setFocusable(true);
        mSetSexPop.setTouchable(true);
        mSetSexPop.setOutsideTouchable(true);
        mSetSexPop.setContentView(mainView);
        mSetSexPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetSexPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetSexPop.setAnimationStyle(R.style.bottomStyle);
        mSetSexPop.showAtLocation(mMainView, Gravity.BOTTOM, 0, 0);
        mSetSexPop.update();

        mainView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mSetSexPop.dismiss();
                return false;
            }
        });

    }
}